package com.star.ms.generation.service.impl;

import com.star.ms.admin.dao.mongodb.ReviewDAO;
import com.star.ms.generation.utils.RandomUtil;
import com.star.ms.admin.service.address.AddressService;
import com.star.ms.admin.service.user.UserService;
import com.star.ms.common.pojo.address.Area;
import com.star.ms.common.pojo.address.City;
import com.star.ms.common.pojo.address.Province;
import com.star.ms.common.pojo.product.Product;
import com.star.ms.common.pojo.user.User;
import com.star.ms.generation.dto.ProductDto;
import com.star.ms.generation.service.RandomService;
import com.star.ms.generation.utils.DateUtil;
import com.star.ms.generation.utils.GeneratorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.*;

@Service
public class RandomServiceImpl implements RandomService {
    private List<Province> provinces = new ArrayList<Province>();
    private Map<String, List<City>> cityMap = new HashMap<>();
    private Map<String, List<Area>> areaMap = new HashMap<>();
    private Random random = new Random();
    private boolean init = false;

    public int maxID = -1;
    @Autowired
    private AddressService addressService;
    @Autowired
    private UserService userService;
    @Autowired
    private ReviewDAO reviewDAO;
    @Override
    public List<User> randomUser(List<String[]> imgs, Integer size) {
        List<User> users = RandomUtil.randomUser(imgs, size);
        // 地址要和数据库交互，所以这里在service层单独生成
        List<String> list = randomAddress(size);
        // 查询数据库中目前最大的主键
        for (int i = 0; i < list.size(); i++) {
            users.get(i).setAddress(list.get(i));
        }
        return users;
    }

    @Override
    public Set<String> randomEmail(int num) {
        return RandomUtil.randomEmail(num, 6);
    }

    /**
     * 随机产生地址
     * @param size
     * @return
     */
    @Override
    public List<String> randomAddress(int size) {
        // 初始化：从数据库里获取地址相关数据
        if(!init){
            provinces = addressService.getProvinces();
            for (Province province : provinces) {
                List<City> cities = addressService.getCityByProvinceCode(province.getCode());
                for (City city : cities) {
                    List<Area> ares = addressService.getAreaByCityCode(city.getCode());
                    areaMap.put(city.getName(), ares);
                }
                cityMap.put(province.getName(), cities);
            }
            init = true;
        }
        List<String> list = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            // 选择省份
            String province = provinces.get(random.nextInt(provinces.size())).getName();
            // 选择城市
            List<City> cities = cityMap.get(province);
            String city = (cities != null && cities.size() > 0) ? cities.get(random.nextInt(cities.size())).getName() : "";
            // 选择地区
            List<Area> areas = areaMap.get(city);
            String area = (areas != null && areas.size() > 0)? areas.get(random.nextInt(areas.size())).getName() : "";
            // 拼接地址
            list.add(String.format("%s-%s-%s-%s",
                    province,
                    city,
                    area,
                    "详细地址"));
        }
        return list;
    }

    public boolean saveRandomUser(List<String[]> imgs, Integer nums) {
        return userService.saveUsersWithRole(randomUser(imgs, nums));
    }

    @Override
    public List<ProductDto> randomProduct(int size) {
        return GeneratorUtil.getProductFromJson("json/1_1.json");
    }

    @Override
    public List<Product> randomProductFormat(String ...fileName) {
        List<Product> list = GeneratorUtil.getProductFromJsonFormat(fileName);
        for (Product p : list) {
            // 设置随机的存货（100起步）
            p.setStock(random.nextInt(1000) + 100L);
            // 设置随机的创建时间
            try {
                p.setCreateTime(DateUtil.getRandomDate("2018-01-01", "2022-05-21"));
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
        return list;
    }

    @Override
    public List<Review> randomReview(String ...jsonFileName) {
        List<Review> list = GeneratorUtil.getReviewsFromJsonFormat(jsonFileName);
        if(maxID == -1)
            maxID = userService.getMaxId();
        // 赋予评论随机的用户ID
        for (Review review : list) {
            review.setReviewsUserId((long) random.nextInt(maxID + 1));
        }
        return list;
    }
    @Override
    public List<Review> randomReviewAndInsert(String ...jsonFileName) {
        return reviewDAO.insertList(randomReview(jsonFileName));
    }

    @Override
    public boolean removeReviews() {
        return reviewDAO.clear();
    }
}
